const {WebSocket} = require('ws')
const createVideoWindow = require("./windows/videowindow");

let localVideoWindow = null
let remoteVideoWindow = null

module.exports = function (id, mainWindow) {
    const ws = new WebSocket("ws://127.0.0.1:8081/w?id=" + id)
    ws.on('open', function open() {
        console.log("success")
    });
    ws.on('message', function (data) {
        let body
        try {
            body = JSON.parse(data)
        } catch {
            console.log("解析出错")
        }
        let type = body.type
        switch (type) {
            case 'isOnline': {
                if (body.isOnline) {
                    if (body.id === id) {
                        localVideoWindow = createVideoWindow(mainWindow, "local")
                        localVideoWindow.on('closed',()=>{localVideoWindow = null})
                        console.log("local")
                    } else {
                        remoteVideoWindow = createVideoWindow(mainWindow, 'remote')
                        remoteVideoWindow.on('closed',()=>{remoteVideoWindow = null})
                        console.log("remote")
                    }
                }
                break
            }
            case 'start': {
                console.log("start")
                localVideoWindow.webContents.send('dataAvailable', body)
                break
            }
            case 'user': {
                mainWindow.webContents.send('msgAvailable', body)
                break
            }
            default : {
                if(remoteVideoWindow != null){
                    remoteVideoWindow.webContents.send('dataAvailable', body)
                }else {
                    localVideoWindow.webContents.send('dataAvailable', body)
                }
            }
        }
    })
    return ws
}
